package top.hcode.hoj.controller.admin;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nutz.lang.util.NutMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.hcode.hoj.common.result.CommonResult;
import top.hcode.hoj.pojo.dto.BaseIdDTO;
import top.hcode.hoj.pojo.dto.QueryStuffDTO;
import top.hcode.hoj.pojo.dto.SaveStuffDto;
import top.hcode.hoj.pojo.vo.StuffTypeCountVO;
import top.hcode.hoj.pojo.vo.StuffVO;
import top.hcode.hoj.service.admin.AdminStuffService;
import top.hcode.hoj.utils.ShiroUtils;

import java.util.List;

/**
 * @author orangej
 * @since 2024/12/31
 */
@Slf4j
@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
public class AdminStuffController {

    private final AdminStuffService stuffService;

    @GetMapping("/stuff/list")
    public CommonResult<IPage<StuffVO>> list(QueryStuffDTO dto) {
        dto.setUid(ShiroUtils.getUid());
        return CommonResult.successResponse(stuffService.queryList(dto));
    }

    @ApiOperation(value = "获取文件列表")
    @GetMapping("/stuff/list/leaf")
    public CommonResult<IPage<StuffVO>> listLeaf(QueryStuffDTO dto) {
        dto.setUid(ShiroUtils.getUid());
        dto.setIsLeaf(true);
        return CommonResult.successResponse(stuffService.queryList(dto));
    }

    @ApiOperation(value = "获取文件树")
    @GetMapping("/stuff/list/tree")
    public CommonResult<IPage<StuffVO>> listDir(QueryStuffDTO dto) {
        dto.setStuffType("dir");
        dto.setUid(ShiroUtils.getUid());
        return CommonResult.successResponse(stuffService.queryList(dto));
    }

    @GetMapping("/stuff/type/stat")
    public CommonResult<List<StuffTypeCountVO>> statByType(QueryStuffDTO dto) {
        dto.setUid(ShiroUtils.getUid());
        return CommonResult.successResponse(stuffService.queryTypeCount(dto));
    }

    @GetMapping("/stuff/detail")
    public CommonResult<StuffVO> detail(BaseIdDTO dto) {
        return CommonResult.successResponse(stuffService.getStuffDetail(dto.getId()));
    }

    @PostMapping("/stuff/save")
    public CommonResult<SaveStuffDto> save(@Validated @RequestBody SaveStuffDto dto) {
        dto.setUid(ShiroUtils.getUid());
        stuffService.saveStuff(dto);
        return CommonResult.successResponse(dto);
    }

    @PostMapping("/stuff/delete")
    public CommonResult<Void> delete(@Validated @RequestBody NutMap map) {
        Validator.validateNotNull(map, "参数不能为空");
        String id = map.getString("id");
        Validator.validateNotEmpty(id, "id不能为空");

        List<String> idList = StrUtil.splitTrim(id, ",");
        stuffService.deleteStuff(idList);
        return CommonResult.successResponse();
    }
}

